package com.kaifamiao.socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThirdClient {

    public static void main(String[] args) throws Exception {

        ExecutorService es = Executors.newScheduledThreadPool(2);

        Scanner sc = new Scanner(System.in);

        final int port = 54321;
        final InetAddress address = InetAddress.getByName("10.0.4.97");
        SocketAddress remoteAddress = new InetSocketAddress( address, port);

        Socket socket = new Socket();

        System.out.println( "准备连接服务器" );
        socket.connect( remoteAddress );
        System.out.println( "服务器连接成功" );

        Callable receiveTask = () -> {
            BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream()));
            String line;
            while( (line=br.readLine()) != null ){
                System.out.println(line);
                System.out.println("请输入向服务器发送的信息");
            }
            return null;
        };

        es.submit(receiveTask);

        Callable sendTask = () -> {
            PrintStream ps = new PrintStream( socket.getOutputStream() );
            while( true ) {
                System.out.println("请输入向服务器发送的信息");
                String content = sc.nextLine();
                if( "bye bye bye bye".equalsIgnoreCase(content) ) {
                    break;
                }
                ps.println(content);
            }
            socket.close();
            sc.close();
            es.shutdown();
            return null;
        };

        es.submit(sendTask);
    }

}
